﻿using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using SeaBattle.Domain.Entities;
using SeaBattle.Domain.Factory;
using SeaBattle.Web.Models.Account;

namespace SeaBattle.Web.Controllers
{
    public class AccountController : Controller
    {
        private IFormsAuthenticationService FormsService { get; set; }
        private IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            base.Initialize(requestContext);
        }

        public ActionResult LogOn()
        {
            return PartialView(new LogOnModel());
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, false);
                    return returnUrl == null ? (ActionResult) RedirectToAction("Index", "Lobby") : Redirect(returnUrl);
                }
                ModelState.AddModelError("", "Неверное имя или пароль.");
            }

            return PartialView(model);
        }

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return PartialView(new RegisterModel());
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    if (!User.Identity.IsAuthenticated)
                    {
                        FormsService.SignIn(model.UserName, false);
                        PlayerFactory.PlayerService.RegisterNewPlayer(new Player(model.UserName,1000));
                        return RedirectToAction("Index", "Home");
                    }
                }
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return PartialView(model);
        }
    }
}
